<template>
  <div class="category">
    <!--显示所有上架的父分类-->
    <ul>
      <li @click="selectFirstCategory({})" :class="{active:!firstCategorySelect.id}">全部</li>
      <li v-for="(category, index) in firstCategoryList"
          :key="index"
          @click="selectFirstCategory(category)"
          :class="{active:firstCategorySelect.id === category.id}"
      >
        {{ category.name }}
      </li>
    </ul>
    <!--  显示父分类下的子分类-->
    <ul v-if="firstCategorySelect.id">
      <li @click="selectSecondCategory({})" :class="{active:!secondCategorySelect.id}">全部</li>
      <li v-for="(category, index) in secondCategoryList"
          :key="index"
          @click="selectSecondCategory(category)"
          :class="{active:secondCategorySelect.id === category.id}"
      >
        {{ category.name }}
      </li>
    </ul>
  </div>
  <div class="goodsList">
    <el-empty v-if="pageInfo.list.length === 0" description="该分类还没有商品" />
    <ul v-else>
      <li v-for="(good, index) in pageInfo.list" :key="index">
        <div class="pic" @click="toGoodsView(good.id)">
          <el-image :src="'/api/file/images/' + good.picList[0].url"/>
        </div>
        <div class="name" @click="toGoodsView(good.id)">{{ good.name }}</div>
        <div class="dscp" @click="toGoodsView(good.id)">{{ good.dscp }}</div>
        <div class="price" @click="toGoodsView(good.id)">￥ {{ good.price }}</div>
        <div class="addBtn">
          <el-button type="primary" @click="addCart(good.id)">加入购物车</el-button>
        </div>
      </li>
    </ul>
  </div>
  <div>
    <el-row class="row-bg" justify="space-evenly">
      <el-col :span="4">
        <el-pagination layout="prev, pager, next" :total="pageInfo.total" :page-size="pageInfo.pageSize"
                       @current-change="getGoods"/>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, watch} from "vue";
import categoryApi from "@/api/categoryApi.js";
import goodsApi from "@/api/GoodsApi.js";
import {ElMessage, ElMessageBox} from "element-plus";
import router from "@/router/index.js";
import {searchStore} from "@/stores/search.js";
import cartApi from "@/api/CartApi.js";
// 通过路径传递的参数
const props = defineProps({
  categoryId: String
})

// 获取搜索框数据
const search = searchStore()
watch(search, () => {
  condition.value.name = search.searchInfo
  getGoods()
})


// 所有需要显示的父分类
const firstCategoryList = ref([])
// 所有要显示的子分类
const secondCategoryList = ref([])
// 被选中的父分类
const firstCategorySelect = ref({})
// 被选中的子分类
const secondCategorySelect = ref({})

// 当前需要获取商品的条件
const condition = ref({
  name:null,
  categoryId:null,
  parentId:null
})

// 页面商品数据
const pageInfo = ref({
  list:[]
})

// 监听参数的变化
watch(props, () => {
  getParent()
  console.log(props.categoryId)
})

// 点击父分类调用的函数
const selectFirstCategory = (category) => {
  // 给选中父分类赋值
  firstCategorySelect.value = category
  // 给子类选中赋初值
  secondCategorySelect.value = {}

  // 给被选中的父分类下的子分类赋值
  if (category.childList) {
    secondCategoryList.value = category.childList
  }
  if (category.id) {
    condition.value.parentId = category.id
    condition.value.categoryId = null
  } else {
    condition.value.parentId = null
    condition.value.categoryId = null
  }

//   查询商品
  getGoods(1)
}

// 点击子分类的时候调用的函数
const selectSecondCategory = (category) => {
  secondCategorySelect.value = category
  if (category.id) {
    condition.value.categoryId = category.id
  } else {
    condition.value.categoryId = null
  }

//   查询商品
  getGoods(1)
}

// 获得上架商品
const getParent = () => {
  categoryApi.getParentInfo(1)
      .then(resp => {
        firstCategoryList.value = resp.data
        // 标识
        let b = 0
        firstCategoryList.value.forEach(c => {
          if (props.categoryId == c.id) {
            b++
            selectFirstCategory(c)
          }
        })
        if (b === 0) {
          condition.value.name = search.searchInfo
          getGoods(1)
        }
      })
}

// 通过分页查询商品
const getGoods = (pageNum) => {
  goodsApi.getGoodsList(condition.value,pageNum,10)
      .then(resp => {
        if (resp.code === 10000) {
          pageInfo.value = resp.data
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

//  跳转到商品详情
const toGoodsView = (id) => {
  router.push({
    path:'/user/goods',
    query:{
      id
    }
  })
}

// 添加购物车
const addCart = (id) => {
  cartApi.addInfo(id)
      .then(resp => {
        if (resp.code === 10000) {
          // ElMessage.success(resp.msg)
          ElMessageBox.confirm(
              '加入成功，是否打开购物车',
              '提示',
              {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'info',
              }
          )
              .then(() => {
                router.push('/user/cart')
              })
              .catch(() => {

              })
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

getParent()
</script>

<style scoped>
.category ul li {
  float: left;
  margin: 10px 20px;
  font-size: 14px;
  cursor: pointer;
}

.category ul li:hover {
  font-weight: bold;
  color: var(--theme-color);
}

.active {
  font-weight: bold;
  color: var(--theme-color);
}

.goodsList ul li {
  width: 224px;
  float: left;
  text-align: center;
  margin-right: 20px;
  margin-bottom: 10px;
  background-color: #EEE;
  cursor: pointer;
}

.goodsList ul li:hover {
  box-shadow: 0px 0px 20px;
  background-color: #716f6f;
}

.goodsList ul li:nth-child(5n) {
  margin-right: 0px;
}

.name {
  font-weight: bold;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dscp {
  color: #AAA;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.recom .price {
  font-size: 14px;
  color: var(--theme-color);
}

.name, .price, .dscp {
  line-height: 25px;
}
</style>